<template>
  <div class="page-main layout-lr page-lionbay">
    <div class="app-container" :style="{height:'100%', minHeight: '500px'}">
      <div class="flex-wrap" :style="{marginRight:isSearch ? '0' : '-24px' }">
        <div class="content-wrap" :class="hadSearch ? 'crosshair' : ''">
          <div id="map" ref="basicMapbox" style="height:100%;width:100%"></div>
          <div class="tips" v-if="hadSearch">
            <div class="hd">{{ tips.title }}</div>
            <div class="bd">
              <img :src="tips.img" height="26" width="100%" />
            </div>
            <div class="ft">
              <span v-for="(item,index) in tips.value" :key="index">{{ item }}</span>
            </div>
          </div>
        </div>        
        <div class="form-search" v-show="isSearch">
          <h3>查询条件</h3>
          <el-form size="small" :model="searchForm" label-width="90px" label-position="top">
            <el-form-item label="水质指标：">
              <el-select v-model="searchForm.tag" placeholder="请选择" style="width:100%;" >
                  <el-option v-for="(item,index) in initData.tag" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="统计类型：">
              <my-dateRange :start.sync="searchForm.start_date" :end.sync="searchForm.end_date" :picker-options="pickerPrediction" style="width:100%;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="getLionbayTile">启动反演</el-button>
              <el-button size="small" @click="resetMap">重置图层</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <echarts-point ref="echartsPoint" @show="data => $refs.showEcharts.init(data)" />
    <echarts-region ref="echartsRegion" @show="data => $refs.showEcharts.init(data)" />
    <show-echarts ref="showEcharts" />
  </div>
    
</template>

<script>
import * as mapboxgl from 'mapbox-gl';
import { stylesV8 } from '@/assets/js/config';
import lionbay from '@/assets/geojson/lionbay';
import lite from '@/assets/geojson/lite';
import echartsPoint from './components/echartsPoint';
import echartsRegion from './components/echartsRegion';
import showEcharts from './components/showEcharts';
export default {
  components:{
    echartsPoint,
    echartsRegion,
    showEcharts,
  },
  data() {
    return {
      isSearch: true,
      hadSearch: false,
      searchForm:{
        tag: 'tn',
        start_date: null,
        end_date: null,
      },
      pickerPrediction:{
        disabledDate:(time) => {
          const pre = new Date('2015-06-23').getTime();
          const next = new Date().getTime();
          return time.getTime() < pre || time.getTime() > next;
        }
      },
      map: null,
      mapboxToken: 'pk.eyJ1Ijoic25zcXNzIiwiYSI6ImNrZ2oxbWtqMTAzNnAyeXFwMDAzdmp2YTAifQ.AuaHmI9j-_VbOYxUSJACQw',
      selStyle: stylesV8[1],
      initData:{
        tag:[
          {id: 'tn', name: '总氮(TN)'},
          {id: 'tp', name: '总磷(TP)'},
          {id: 'nh3_n', name: '氨氮(NH3-N)'},
          {id: 'd_o', name: '解氧(DO)'},
          {id: 'turbidity', name: '浊度(NTU)'},
          {id: 'ph', name: '酸碱度(pH)'},
          {id: 'codmn', name: '高锰酸盐指数(CODmn)'},
          {id: 'temp', name: '水温(TEMP)'},
        ]
      },
      tips:{
        title: '总氮(TN)(mg/L)',
        img: require('@/assets/images/img-color.png'),
        value: [3.4673,3.6736,3.8799],
      }
 
    }
  },
  created(){
    let d = this.$moment().subtract(1, 'years').format('YYYY-MM-DD');
    this.searchForm.start_date = this.$moment(d).add(1, 'd').format('YYYY-MM-DD');
    this.searchForm.end_date = this.$moment().format('YYYY-MM-DD');
    // this.getLionbayTile();
    // this.getPointSeries();
    // this.$refs.echartsInfo.init(data)
  },
  mounted(){
    this.$nextTick(() => {
      var map = new mapboxgl.Map({
        accessToken: 'pk.eyJ1Ijoic25zcXNzIiwiYSI6ImNrZ2oxbWtqMTAzNnAyeXFwMDAzdmp2YTAifQ.AuaHmI9j-_VbOYxUSJACQw',
        container: 'map',
        // style: 'mapbox://styles/mapbox/streets-v8',
        style: {
            version: 8,
            name: 'BlankMap',
            glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
            sources: {},
            layers: [
              {
                id: 'background',
                type: 'background',
                paint: {
                  'background-color': '#f0f2f5'
                }
              },
              {
                id: 'split-layer',
                type: 'background',
                paint: {
                  'background-color': 'rgba(0,0,0,0)'
                }
              },
            ]
          },
        center: [113.5,22.9], // 设置地图中心点的经纬度
        zoom: 10 // 设置地图缩放级别
      });
      map.on('load', () => {
        this.map = map;
        this.addStyleRaster();
        this.addBorder();
        this.addBlock();
        this.addTileLayer('https://earthengine.googleapis.com/v1/projects/earthengine-legacy/maps/919a62893b9afa3e4ce8974342b054e1-52fa58db7c5180c20f48bc63eec6287c/tiles/{z}/{x}/{y}')
        // this.clickOnMap();
      });
    })
    
  },
  methods:{
    addStyleRaster(){
      const styles = this.selStyle.url.split('/');
      this.map.addSource('basemap-style-source', {
        type: 'raster',
        scheme: 'xyz',
        tiles: [
          `https://api.mapbox.com/styles/v1/snsqss/${styles[styles.length - 1]}/tiles/512/{z}/{x}/{y}?access_token=${this.mapboxToken}`
        ]
      })
      this.map.addLayer({
        id: 'basemap-style-layer',
        type: 'raster',
        source: 'basemap-style-source',
        layout: {}
      }, 'split-layer');
    },
    addBorder(){
      if (this.map.getLayer('area-border')) {
        this.map.removeLayer('area-border');
      }
      if (!this.map.getLayer('area-border')) {
        this.map.addLayer({
          id: 'area-border',
          type: 'line',
          source: {
            type: 'geojson',
            data: lionbay
          },
          minzoom: 1,
          maxzoom: 19,
          paint: {
            'line-color': '#ff0000',
            'line-width': 1
          }
        }, this.map.getLayer('split-layer') ? 'split-layer' : undefined);
      }      
    },
    addBlock(){
      if (this.map.getLayer('area-block')) {
        this.map.removeLayer('area-block');
      }
      if (!this.map.getLayer('area-block')) {
        this.map.addLayer({
          id: 'area-block',
          type: 'fill',
          source: {
            type: 'geojson',
            data: lionbay
          },
          paint: {
            'fill-color': '#43a543',
            'fill-opacity': 0,
            // 'fill-outline-color': '#000',
          },
        }, this.map.getLayer('area-border') ? 'area-border' : undefined);
      }      
    },
    addTileLayer(url){
      // 添加在线瓦片图层	
      if (this.map.getLayer('tile_layer')) {
        this.map.removeLayer('tile_layer');
      }
      if (this.map.getSource('tile_source')) {
        this.map.removeSource('tile_source')
      }
      this.map.addSource('tile_source', {
          type: 'raster',
          tiles: [url], // 替换为您的在线瓦片URL
          tileSize: 256
      });
      this.map.addLayer({
          id: 'tile_layer',
          type: 'raster',
          source: 'tile_source',
          paint: {}
      },'split-layer');
      this.moveOnMap();
      this.clickOnMap();
    },
    moveOnMap(){
      if (!this.map) {
        return;
      }
      console.log('图层',this.map.getStyle().layers);
      this.map.on('mousemove', (e) => {
        const features = this.map.queryRenderedFeatures(e.point, {layers: ['area-block']});
        if(features.length > 0){
          this.map.getCanvas().style.cursor = 'crosshair'
        }
      });
      this.map.on('mouseleave', 'area-block', (e) => {
        this.map.getCanvas().style.cursor = 'default'
      });
    },
    clickOnMap(){
      if (!this.map) {
        return;
      }
      console.log('图层',this.map.getStyle().layers);
      this.map.on('click', (e) => {
        const features = this.map.queryRenderedFeatures(e.point, {layers: ['area-block']});
        if(features.length > 0){
          let params = {
            map_lon: e.lngLat.lng,
            map_lat: e.lngLat.lat,
            tag: this.searchForm.tag
          };
          this.$refs.echartsPoint.init(params);
        }else{
          console.log('无效区域')
        }
      });
    },
    
    getLionbayTile(){
      this.$request('post', '/lionbay/get_lionbay_tile', this.searchForm, (data,msg) => {
        this.tips.title = data.titles + data.units;
        this.tips.value = [data.vismax.fixed(3), ((data.vimin+data.vismax)/2).fixed(3),data.vismax.fixed(3)];
        this.$forceUpdate();
       console.log(this.tips);
       this.hadSearch = true;
        let url = data.local_url.split('api-gee');
        this.addTileLayer('/api-gee' + url[1]);
      },msg => {

      }, {}, 'all');
      this.getRegionSeries();
    },
    getRegionSeries(){
      this.$request('post', '/lionbay/get_region_series', {tag:this.searchForm.tag}, (data,msg) => {
        this.$refs.echartsRegion.init(data);
      }, msg => {

      }, {}, 'all');
    },
    resetMap(){
      this.hadSearch = false;
      this.searchForm.tag = 'tn';
      let d = this.$moment().subtract(1, 'years').format('YYYY-MM-DD');
      this.searchForm.start_date = this.$moment(d).add(1, 'd').format('YYYY-MM-DD');
      this.searchForm.end_date = this.$moment().format('YYYY-MM-DD');
      this.$refs.echartsRegion.handleClose();
      this.$refs.echartsPoint.handleClose();
      if (!this.map) {
        return;
      }
      if (this.map.getLayer('tile_layer')) {
        this.map.removeLayer('tile_layer');
      }
      if (this.map.getSource('tile_source')) {
        this.map.removeSource('tile_source')
      }
    }
    
  }
}
</script>